/*
*    Author : heiden deng(dengjianquan@beyondcent.com)
*    2017/08/03
*    version 0.0.9
*    pick first负载均衡处理类方法定义
*/
#include "PickfirstLB.h"
#include "htsc_registry/registry_utils.h"
#include "htsc_grpc_consumer_utils.h"
//addbyhuyn
#include "htsc_grpc_consumer_control_version.h"

PickfirstLB::PickfirstLB()
{
}


PickfirstLB::~PickfirstLB()
{
}

provider_t* PickfirstLB::chooseProvider(const char* sn, int step) {
	int index = 0;
	int index_org = index;
	if (!providers || !sn)
	{
		return NULL;
	}
	std::map<std::string, std::vector<provider_t*> >::iterator provider_lst_iter = providers->find(sn);
	if (provider_lst_iter == providers->end())
	{
		return NULL;
	}
	int size = provider_lst_iter->second.size();
	if (size > 0)
	{
		bool do_while = true;
		bool is_invalid = true;
		int index_valid = -1;
		while (do_while)
		{
			is_invalid = is_provider_invalid(provider_lst_iter->second[index]);
			if (is_invalid == false) { //查找到未禁用的服务
									   //根据服务名和版本号校验是否匹配
				if (htsc_grpc_consumer_control_version_match(provider_lst_iter->second[index]->sInterface, provider_lst_iter->second[index]->version) == true) {
					index_valid = index;
					break;   //找到未禁用，并且版本匹配的服务
				}
				else if (index_valid < 0) { //记录首个未禁用的服务
					index_valid = index;
				}
			}
			index = (index + 1) % size;
			if (index == index_org)
			{
				if (index_valid >= 0) {
					break;
				}
				else {
					return NULL;//没有合适的provider
				}
			}
		}
		return clone_provider(provider_lst_iter->second[index_valid]);
	}
	return NULL;

}
void PickfirstLB::setProviders(std::map<std::string, std::vector<provider_t*> > *_providers) {
	this->providers = _providers;
}

void PickfirstLB::resetCursor(const char* sn) {
	return;
}